package com.kiliter.config;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collections;

/**
 * Description: 将逗号隔开的字符串序列化成数组，当然也可以换成其他符号隔开的字符串
 * 配合@Jsonserializer（using = StringToArrayJsonSerializer.class）即可
 * @author zhangjl
 * @date 2021/6/18 15:47
 */
@Component
public class StringToArrayJsonSerializer extends JsonSerializer<String> {


    @Override
    public void serialize(String s, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (StrUtil.isEmpty(s)) {
            jsonGenerator.writeObject(Collections.emptyList());
        } else {
            jsonGenerator.writeObject(s.split(","));
        }
    }
}
